package com.fortune.service.acl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fortune.common.acl.CacheKeyConstants;
import com.fortune.common.redis.RedisClient;
import com.fortune.constants.redis.CacheKeys;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class MCacheService {

//    @Resource(name = "redisPool")
//    private RedisPool redisPool;
    @Autowired
    private RedisClient redisClient;

    public void saveCache(String toSavedValue, int timeoutSeconds, CacheKeyConstants prefix) {
        saveCache(toSavedValue, timeoutSeconds, prefix, new String[] {});
    }

    public void saveCache(String toSavedValue, int timeoutSeconds, CacheKeyConstants prefix, String... keys) {
//        if (toSavedValue == null) {
//            return;
//        }
//        ShardedJedis shardedJedis = null;
//        try {
//            String cacheKey = generateCacheKey(prefix, keys);
//            shardedJedis = redisPool.instance();
//            shardedJedis.setex(cacheKey, timeoutSeconds, toSavedValue);
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < keys.length; i++) {
            	sb.append(keys[i]);
            	sb.append("_");
			}
            redisClient.save(toSavedValue, timeoutSeconds/60, CacheKeys.valueOf(prefix.name()), sb.toString());
//        } catch (Exception e) {
//            log.error("save cache exception, prefix:{}, keys:{}", prefix.name(), JsonMapper.obj2String(keys), e);
//        } finally {
//            redisPool.safeClose(shardedJedis);
//        }
    }

    public String getFromCache(CacheKeyConstants prefix, String... keys) {
//        ShardedJedis shardedJedis = null;
//        String cacheKey = generateCacheKey(prefix, keys);
//        try {
//            shardedJedis = redisPool.instance();
//            String value = shardedJedis.get(cacheKey);
//            return value;
//        } catch (Exception e) {
//            log.error("get from cache exception, prefix:{}, keys:{}", prefix.name(), JsonMapper.obj2String(keys), e);
//            return null;
//        } finally {
//            redisPool.safeClose(shardedJedis);
//        }
    	 StringBuffer sb = new StringBuffer();
         for (int i = 0; i < keys.length; i++) {
         	sb.append(keys[i]);
         	sb.append("_");
			}
         return redisClient.get(CacheKeys.valueOf(prefix.name()), sb.toString());
    }

//    private String generateCacheKey(CacheKeyConstants prefix, String... keys) {
//        String key = prefix.name();
//        if (keys != null && keys.length > 0) {
//            key += "_" + Joiner.on("_").join(keys);
//        }
//        return key;
//    }
}
